var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var tpl = require('../tpl');

var servant = require('../i18n/servant')
var i18n = require('../i18n');
var util = require('imutil');
var config = require('../webim.config');
var bus = require('bus');
var dialog = require('dialog');
var Adapter = require('adapter')
var logger = require('logger');


module.exports = Backbone.View.extend({
	el: null,
	template:tpl.profile,
	initialize: function(options, api, uid){
        this.uid = uid;
		this.api = api;
		this.render();
		//logger.log(arguments);
        this.listenTo(bus, 'moreProfile',function(){
            var that = this;
			
            this.api.mask.show();
			var $mask = this.api.mask.content(tpl.block(servant.fuse({isBlocked: this.api.sdk.isBlocked(this.uid)}, i18n.block)));
			
			var stop = function(e){
				e.preventDefault();
				e.stopPropagation();
			};
			
			$('.J-btn-block', $mask).click(function(e){
				stop(e);
				
				dialog.confirm('Attention', 'Block This Contract?', function(){
					that.api.sdk.block(that.uid,function(){
						that.api.mask.hide();
                        dialog.tip('Successful', 'Add contact to the blacklist successfully.')
							.time(3);
                    });
				}, function(){
					//dialog.tip('Fail', 'Add contact to the blacklist Failed.')
					//		.time(3);
					//that.api.mask.hide();
				});
			});
			
			$('.J-btn-unblock', $mask).click(function(e){
				stop(e);
				
				dialog.confirm('Attention', 'Unblock This Contract?', function(){
					that.api.sdk.unblock(that.uid,function(){
						that.api.mask.hide();
                        dialog.tip('Successful', 'Remove contact from the blacklist successfully.')
							.time(3);
						
                    });
				}, function(){
					//dialog.tip('Fail', 'Remove contact from the blacklist Failed.')
					//		.time(3);
					//that.api.mask.hide();
				});
			});
			
			$('.J-btn-cancel', $mask).click(function(e){
				stop(e);
				that.api.mask.hide();
			});
        });
		
        this.listenTo(this.api.mask, 'hide',function(){
            this.api.mask.empty();
        });
		
		this.listenTo(bus, 'statusChange', function(uid, isOnline){
			if(this.api.isGetContacts && uid === this.uid){
				this.$('.J-im-isOnline').removeClass('im-dot-online im-dot-offline').addClass(isOnline ? 'im-dot-online' : 'im-dot-offline');
			}
		});
	},

	render: function(){
        var _this = this;
        var ad = new Adapter({
            "name": "fullName"
        });
        
		this.api.ready(function(){
			_this.api.sdk.getProfile(_this.uid, function(user){
			   var content = ad.parse(user);

				_this.$el.append(_this.template(content));
			});
		});
    }
});


